module.exports = {
    websockman : function(){
        this.sockets = {};//list of sockets by user PubID;
        
        this.onConnect = function(socket){
            var pubID = this.createPubID();
            this.sockets[pubID] = socket;
              
            socket.on('error', function(error) {
                socket.send('{"ERR": "ERREUR dans la requete"}');
                throw error;
            });
            
            socket.on('message', function(data) {
                var json = JSON.parse(data);
                if (json.HELO) {
                    var json = {
                        "WLCM": {
                            "PUB_ID" : pubID,
                            "MOTD": "Bienvenue sur le serveur de chat de test"
                            }
                        };
                    socket.send(JSON.stringify(json));
                }else{
                    main.dispatcher.dispatch(json);
                }
            });
              
            socket.on('close', function(data) {
                delete(this.sockets[pubID]);
                if (data != "" && data != null) {
                    var json = JSON.parse(data);
                    if (json) {
                        main.dispatcher.dispatch(json);
                    }
                }
            });
        };
        
        this.send = function(pubID, json){
            if (this.sockets[pubID]) {
                this.sockets[pubID].send(json);
            }
        }
        
        this.sendToAll = function(json){
            for( pubID in this.sockets){
                this.sockets[pubID].send(json);
            }
        }
        
        this.createPubID = function(){
            var n=Math.floor(Math.random()*11);
            var k = Math.floor(Math.random()* 1000000);
            var m = String.fromCharCode(n)+k;
            return m;
        }
    }
}